package hoang.android.app.network;

import hoang.android.app.info.WebServiceConfig;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;

public class AsyncHttpGet extends AsyncHttpBase{

	public AsyncHttpGet(Context context, AsyncHttpResponseListener listener,
			List<NameValuePair> params) {
		super(context, listener, params);
		// TODO Auto-generated constructor stub
	}

	public AsyncHttpGet(Context context, AsyncHttpResponseProcess httpResponseProcess, List<NameValuePair> params){
		super(context, httpResponseProcess, params);
	}
	
	@Override
	protected String request(String url) {
		
		try {
			HttpParams params = new BasicHttpParams();
			if(parameter!=null){
				Iterator<NameValuePair> iterator = parameter.iterator();
				int i=0;
				while(iterator.hasNext()){
					NameValuePair nv = iterator.next();
					params.setParameter(nv.getName(), nv.getValue());
					if(i==0){
						url += "?" + nv.getName()+"="+nv.getValue();
						//url += "?" + URLEncoder.encode(nv.getName()+"="+URLEncoder.encode(nv.getValue()));
					}else{
						url += "&" + nv.getName()+"="+nv.getValue();
						//url += "&" + URLEncoder.encode(nv.getName()+"="+URLEncoder.encode(nv.getValue()));
					}
					i++;
				}
			}
			
			HttpConnectionParams.setSoTimeout(params, WebServiceConfig.NETWORK_TIMEOUT);
			HttpConnectionParams.setConnectionTimeout(params, WebServiceConfig.NETWORK_TIMEOUT);
			
			HttpClient httpClient = creatHttpClient(params);
			HttpGet httpGet = new HttpGet(url);
			
			try {
				response = httpClient.execute(httpGet);
				statusCode = STATUS_NETWORK_OK;
			} catch (java.net.SocketTimeoutException e) {
				statusCode = STATUS_NETWORK_TIMEOUT;
			} catch (javax.net.ssl.SSLException e) {
				statusCode = STATUS_NETWORK_EXCEIPTION;
			} catch (org.apache.http.conn.ConnectionPoolTimeoutException e) {
				statusCode = STATUS_NETWORK_TIMEOUT;
			} catch (ClientProtocolException e) {
				statusCode = STATUS_NETWORK_ERROR;
			} catch (IOException e) {
				statusCode = STATUS_NETWORK_ERROR;
			} catch (Exception e) {
				statusCode = STATUS_NETWORK_EXCEIPTION;
			}
			
		} catch (Exception e) {
			statusCode = STATUS_NETWORK_EXCEIPTION;
		}
		
		return super.request(url);
	}
	
}
